using System;
using CommonDomain.Persistence;

namespace Sponsorship.Domain.MembershipTypes
{
    /// <summary>
    /// Handles domain commands dealing with <see cref="MembershipType"/> instances.
    /// </summary>
    public class MembershipTypeCommandHandler :
        ICommandHandler<EnterMembershipType>,
        ICommandHandler<ChangeMembershipType>,
        ICommandHandler<DeleteMembershipType>
    {
        private readonly IRepository _repository;

        public MembershipTypeCommandHandler (IRepository repository)
        {
            _repository = repository;
        }

        public void Handle (EnterMembershipType command)
        {
            var membershipType = new MembershipType (command.MembershipTypeId, command.Name, command.Amount, command.Period, command.Comment);

            //save new raised events of aggregate into eventstore
            SaveMembershipType (membershipType);
        }

        public void Handle (ChangeMembershipType command)
        {
            MembershipType membershipType = LoadMembershipType(command.MembershipTypeId, command.Version);

            //execute domain logic and get back a new aggregate
            membershipType.Delete();

            //save new raised events of aggregate into eventstore
            SaveMembershipType (membershipType);
        }

        public void Handle (DeleteMembershipType command)
        {
            MembershipType membershipType = LoadMembershipType(command.MembershipTypeId, command.Version);

            //execute domain logic and get back a new aggregate
            membershipType.Delete();

            //save new raised events of aggregate into eventstore
            SaveMembershipType (membershipType);
        }

        //private SponsorshipType LoadSponsorshipType(Guid guid)
        //{
        //    return _repository.GetById<SponsorshipType>(guid);
        //}

        private MembershipType LoadMembershipType (Guid guid, int version)
        {
            return _repository.GetById<MembershipType> (guid, version);
        }

        private void SaveMembershipType (MembershipType sponsorship)
        {
            _repository.Save (sponsorship, Guid.NewGuid()); // Every commit has a new ID
        }
    }
}